package com.wy.springbootblog.interceptors;

import com.wy.springbootblog.util.JwtUtil;
import com.wy.springbootblog.util.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 作者：吴耀
 * 时间：2023/12/24 21:46
 * 描述：
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    // 拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 忽略静态资源请求/upload/images/1_23-12-29_16cd1361-0bd9-4.png
        String url = request.getRequestURI();
        String[] prefixArray = {"/upload"};
        for (String prefix : prefixArray) {
            if (url.startsWith(prefix)) {
                return true;
            }
        }
        // 1.获取token
        String token = request.getHeader("Authorization");
        // 2.校验token
        try {
            // 解析token业务数据
            Map<String,Object> map = JwtUtil.parseToken(token);
            // 将业务数据存储到ThreadLocal中进行共享
            ThreadLocalUtil.set(map);
            return true;
        } catch (Exception e) {
            // http状态码为401
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 完成后，清楚ThreadLocal中的数据，防止内存泄露
        ThreadLocalUtil.remove();
    }
}
